package com.gfl.trivialrestclient.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandlerImpl;

import com.gfl.trivialrestclient.controllers.forms.AjaxSubmitionStatus;

public class AjaxAccessDeniedHandler extends AccessDeniedHandlerImpl {
	private String ajaxErrorPage;

	public void setAjaxErrorPage(String ajaxErrorPage) {
		this.ajaxErrorPage = ajaxErrorPage;
	}

	@Override
	public void handle(HttpServletRequest request,
			HttpServletResponse response,
			AccessDeniedException accessDeniedException) throws IOException,
			ServletException {
		// detect ajax request
		if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
			String redirectUrl = request.getContextPath() + ajaxErrorPage;

			response.setContentType("application/json; charset=UTF-8");

			AjaxSubmitionStatus successStatus = new AjaxSubmitionStatus(false);
			successStatus.setTargetUrl(redirectUrl);
			successStatus.setErrorMessage(accessDeniedException.getMessage());

			response.getWriter().print(
					new ObjectMapper().writeValueAsString(successStatus));

			response.getWriter().flush();
		} else {
			// traditional html success
			super.handle(request, response, accessDeniedException);
		}

	}
}
